﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ST.Core;

namespace ST.ModelVM.ProtocolDefine
{
    public class ProtocolXHSJVM:Int64Model
    {
        public string Name { get; set; } = string.Empty;
        public byte Gnm { get; set; }
        public UInt16 StartAddress { get; set; }

        public UInt16 EndAddress { get; set; }
        public bool BitData { get; set; }
        public UInt16 ReqNum { get; set; }



        public List<ProtocolXHSJRowVM> Data { get; set; } = new List<ProtocolXHSJRowVM>();


        public List<List<PropValue>> PropValue { get; set; } = new List<List<PropValue>>();

        [JsonIgnore] 
        public byte[] Bytes { get; set; } = new byte[1];

        public void CreateBytes()
        {
            var total = 0;
            for (var ir = 0; ir < PropValue.Count; ir++)
            {
                var datarow = PropValue[ir];
                for (var i = 0; i < Data.Count; i++)
                {
                    var mPropValue = datarow[i];
                    var o = Data[i];
                    mPropValue.DataType = o.DataType;
                    
                    switch (o.DataType)
                    {
                        case "Bit":
                        case "Byte":
                            mPropValue.Index = total;
                            total++;
                            break;
                        case "UInt16":
                            mPropValue.Index = total;
                            total += 2;
                            break;
                        case "Int":
                            mPropValue.Index = total;
                            total += 4;
                            break;
                        case "Float":

                            mPropValue.Index = total;
                            total += 4;
                            break;
                        default:
                            break;

                    }
                }
            }

            this.Bytes = new byte[total];
            this.EndAddress = Convert.ToUInt16(this.StartAddress + total);
            if (!this.BitData)
            {
                this.EndAddress = Convert.ToUInt16(this.StartAddress + total / 2);
            }
            for (var ir = 0; ir < PropValue.Count; ir++)
            {
                var datarow = PropValue[ir];
                for (var i = 0; i < datarow.Count; i++)
                {
                    var mPropValue = datarow[i];
                    ST.Core.Util.ByteUtil.WriteModbusData(this.Bytes, mPropValue.DataType, mPropValue.NumValue.ToString(), mPropValue.Index);
                }

            }

        }
    }
}
